const path = require('path');
const tools = require('../utils/tools');
const chalk = require('chalk');
const fs = require('fs');
const ora = require('ora');
const { setChoices } = tools;
const loading = ora('生成中...');
const input = async () => {
  const tempObj = {
    type: 'input',
    name: '请输入项目名称!',
    message: '请输入项目名称!',
    default: '',
  };
  const tempResult = await setChoices(tempObj);
  return tempResult;
};
const getFilePath = (projectName, pathDetails = '') =>
  path.resolve(process.cwd(), `./${projectName}${pathDetails}`);
const create = async projectName => {
  loading.start();
  // 建立根目录
  try {
    fs.mkdirSync(getFilePath(projectName));
  } catch (error) {
    loading.fail();
    console.log(chalk.red('请检查项目名称是否重复!'));
    return;
  }
  //  建立方案
  fs.mkdirSync(getFilePath(projectName, '/方案'));
  //  建立过程问题
  fs.mkdirSync(getFilePath(projectName, '/过程问题'));
  //  建立自测
  fs.mkdirSync(getFilePath(projectName, '/自测'));
  const devScheme = fs
    .readFileSync(path.join(__dirname, '../template/devScheme.md'), 'utf-8')
    .replaceAll('{projectName}', projectName);
  const processProblem = fs
    .readFileSync(
      path.join(__dirname, '../template/processProblem.md'),
      'utf-8'
    )
    .replaceAll('{projectName}', projectName);
  const selfTestDoc = fs
    .readFileSync(path.join(__dirname, '../template/selfTestDoc.md'), 'utf-8')
    .replaceAll('{projectName}', projectName);
  //  创建方案文件
  fs.writeFile(
    getFilePath(projectName, `/方案/${projectName}开发方案.md`),
    devScheme,
    () => {}
  );
  const publishProcess = fs.readFileSync(
    path.join(__dirname, '../template/publishProcess.drawio')
  );
  const rollbackProcess = fs.readFileSync(
    path.join(__dirname, '../template/rollbackProcess.drawio')
  );
  fs.writeFile(
    getFilePath(projectName, '/方案/发布流程.drawio'),
    publishProcess,
    () => {}
  );
  fs.writeFile(
    getFilePath(projectName, `/方案/回退流程.drawio`),
    rollbackProcess,
    () => {}
  );
  //  创建过程问题文件
  fs.writeFile(
    getFilePath(projectName, `/过程问题/${projectName}过程问题.md`),
    // getProcessProblemDoc(projectName),
    processProblem,
    () => {}
  );
  //  创建自测文档文件
  fs.writeFile(
    getFilePath(projectName, `/自测/${projectName}自测文档.md`),
    // getSelfTestDoc(projectName),
    selfTestDoc,
    () => {}
  );
  loading.succeed();
  console.log(chalk.green('生成成功!'));
};
const index = async param => {
  const projectName = param || (await input());
  create(projectName);
};
module.exports = index;
